Data set and_vertebrates with measurements of a trout and 2 salamander species in different forest sections.
and_vertebrates#> # A tibble: 32,191 × 6#> year section unittype species length_1_mm weight_g#> <dbl> <chr> <chr> <chr> <dbl> <dbl>#> 1 1987 CC R Cutthroat trout 58 1.75#> 2 1987 CC R Cutthroat trout 61 1.95#> 3 1987 CC R Cutthroat trout 89 5.6 #> 4 1987 CC R Cutthroat trout 58 2.15#> 5 1987 CC R Cutthroat trout 93 6.9 #> 6 1987 CC R Cutthroat trout 86 5.9 #> 7 1987 CC R Cutthroat trout 107 10.5 #> 8 1987 CC R Cutthroat trout 131 20.6 #> 9 1987 CC R Cutthroat trout 103 9.55#> 10 1987 CC R Cutthroat trout 117 13 #> # ℹ 32,181 more rows
labs: Change axis and legend titles and add plot title
g <- g +labs(x ="Length [mm]", y ="Weight [g]",color ="Species", title ="Length-Weight relationship",subtitle ="There seems to be an exponential relationship", caption ="Data from the `lterdatasampler` package" ) g
theme_*: change appearance
ggplot2 offers many pre-defined themes that we can apply to change the appearance of a plot.
g +theme_classic()
g +theme_bw()
theme_*: change appearance
ggplot2 offers many pre-defined themes that we can apply to change the appearance of a plot.
g +theme_minimal()
g +theme_dark()
theme(): customize theme
You can manually change a theme or even create an entire theme yourself. The elements you can control in the theme are:
titles (plot, axis, legend, …)
labels
background
borders
grid lines
legends
If you want a full list of what you can customize, have a look at
?theme
Look here for an overview of the elements that you can change and the corresponding functions
theme(): customize theme
To edit a theme, just add another theme() layer to your plot.
You can set a global theme that will be applied to all ggplot objects in the current R session.
# Globally set theme_minimal as the default themetheme_set(theme_minimal())
Add this to the beginning of your script.
You can also specify some defaults, e.g. the text size:
theme_set(theme_minimal(base_size =16))
This is very practical if you want to achieve a consistent look, e.g. for a scientific journal.
ggsave()
A ggplot object can be saved on disk in different formats.
Without specifications:
# save plot g in img as my_plot.pdfggsave(filename ="img/my_plot.pdf", plot = g)# save plot g in img as my_plot.pngggsave(filename ="img/my_plot.png", plot = g)
Or with specifications:
# save a plot named g in the img directory under the name my_plot.png# with width 16 cm and height 9 cmggsave(filename ="img/my_plot.png",plot = g,width =16,heigth =9,units ="cm")